import 'dart:convert';

import 'package:dio/dio.dart';


class DioManager {
  /*
   * 单利模式
   * */
  Dio _dio = new Dio();
  static DioManager _instance;
  static DioManager getInstance(){
    if(_instance == null){
      _instance = DioManager();
    }
    return _instance;
  }
  DioManager(){
    //连接超时
    _dio.options.connectTimeout = 15000;
    //接收超时
    _dio.options.receiveTimeout = 15000;
    //日志拦截
    // _dio.interceptors.add(LogInterceptor(requestBody: AppConfig.isDebug));
  }

  get(String url,Map params,Function successCallback,Function errorCallback) async{
    _dio.options.headers = {
      "version": "1.1",
    };
    _requstHttp(url, successCallback, 'get', params, errorCallback);
  }
  //post请求
  post(String url, params,Function successCallBack,Function errorCallBack) async {
    //可做加密操作
//    var postBody = Map<String, dynamic>.from({'accessSecretData':Uri.encodeComponent(encrypted.base64)});
    _requstHttp(url, successCallBack, "post", params, errorCallBack);
  }

  _requstHttp(String url, Function successCallBack,
      [String method, Map params, Function errorCallBack]) async {
    Response response;
    _dio.options.connectTimeout = 15000;
    _dio.options.receiveTimeout = 15000;
    try {
      if (method == 'get') {
        if (params != null ) {
          response = await _dio.get(url, queryParameters: params);
        } else {
          response = await _dio.get(url);
        }
      }
      else if (method == 'post') {
        if (params != null) {
          response = await _dio.post(url, queryParameters: params);
        } else {
          response = await _dio.post(url);
        }
      }
    }
    on DioError catch(error) {
      // 请求错误处理
      Response errorResponse;
      if (error.response != null) {
        errorResponse = error.response;
      } else {
        errorResponse = new Response(statusCode: 666);
      }
      // 请求超时
      // if (error.type == DioErrorType.CONNECT_TIMEOUT) {
      //   errorResponse.statusCode = ResultCode.CONNECT_TIMEOUT;
      // }
      // // 一般服务器错误
      // else if (error.type == DioErrorType.RECEIVE_TIMEOUT) {
      //   errorResponse.statusCode = ResultCode.RECEIVE_TIMEOUT;
      // }

      // debug模式才打印
//       if (AppConfig.isDebug) {
//
//         print('请求异常: ' + error.toString());
//         print('请求异常url: ' + url);
//         print('请求头: ' + _dio.options.headers.toString());
// //        print('method: ' + dio.options.method);
//       }
      _error(errorCallBack, error.message);
      return '';
    }
    // debug模式打印相关数据
    // if (AppConfig.isDebug) {
    //   print('请求url: ' + url);
    //   print('请求头: ' + _dio.options.headers.toString());
    //   if (params != null) {
    //     print('请求参数: ' + params.toString());
    //   }
    //   if (response != null) {
    //     print('返回参数: ' + response.toString());
    //   }
    // }
    Map dataMap;
    if (json.decode(response.toString()).runtimeType ==List().runtimeType){
      dataMap = Map();
      dataMap['data'] = json.decode(response.toString());
    }
    else {
      dataMap = json.decode(response.toString());
    }
    if (dataMap == null) {
      _error(errorCallBack, '错误码：' + dataMap['code'].toString() + '，' + response.data.toString());
    }else if (successCallBack != null) {
      successCallBack(dataMap);
    }
  }
  _error(Function errorCallBack, String error) {
    if (errorCallBack != null) {
      errorCallBack(error);
    }
  }
}
